package com.huluobo.h3kotlinproject.detail

import android.content.Context
import android.util.Log
import android.widget.ImageView
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.huluobo.h3kotlinproject.R
import com.huluobo.h3kotlinproject.base.BaseMVVMFragment
import com.huluobo.h3kotlinproject.databinding.FragmentDetailBinding
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader

class DetailFragment : BaseMVVMFragment<FragmentDetailBinding>() {
    lateinit var detailViewModel: DetailViewModel
    private var goodsId: Int = 0
    override fun getLayoutId(): Int = R.layout.fragment_detail

    override fun initData() {
        detailViewModel = ViewModelProvider(requireActivity())[DetailViewModel::class.java]

        detailViewModel.getGoodsId().observe(this) {
            detailViewModel.getGoodsDetail(it)
            goodsId = it
        }

        detailViewModel.detailSuccess.observe(this) {
            dataBinding.goods = it.data
            dataBinding.detailBanner.setImages(it.data.bannerList)
            dataBinding.detailBanner.start()

            com.huluobo.h3kotlinproject.util.ImageLoader.loadImage(
                requireContext(),
                it.data.goods_detail_one,
                dataBinding.detailDetail1
            )

            com.huluobo.h3kotlinproject.util.ImageLoader.loadImage(
                requireContext(),
                it.data.goods_detail_two,
                dataBinding.detailDetail2
            )
        }

        detailViewModel.addToCartSuccess.observe(this) {
            ToastUtils.showLong(it.message)
        }
    }

    override fun initView() {
        //初始化banner
        //设置banner风格
        dataBinding.detailBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
        //设置banner的图片读取器
        dataBinding.detailBanner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (context != null && imageView != null) {
                    Glide.with(context).load(path).into(imageView)
                }
            }
        })
        //设置翻页时间
        dataBinding.detailBanner.setDelayTime(1500)
        //设置指示器位置
        dataBinding.detailBanner.setIndicatorGravity(BannerConfig.CENTER)

        //设置添加购物车的点击事件
        dataBinding.detailAddToCart.setOnClickListener {
            detailViewModel.addToCart(1, goodsId)
        }
    }
}